package tn.talan.xdocreport.generationofreports;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import tn.talan.xdocreport.model.Developer;
import tn.talan.xdocreport.model.Project;

import fr.opensagres.xdocreport.converter.Options;
import fr.opensagres.xdocreport.core.XDocReportException;
import fr.opensagres.xdocreport.document.IXDocReport;
import fr.opensagres.xdocreport.document.images.IImageProvider;
import fr.opensagres.xdocreport.document.registry.XDocReportRegistry;
import fr.opensagres.xdocreport.template.IContext;
import fr.opensagres.xdocreport.template.TemplateEngineKind;
import fr.opensagres.xdocreport.template.formatter.FieldsMetadata;

public class GenerateDocxReport implements GenererDocument {

	public Boolean genrateReport(String nametemplate, String nameoutput,
			Map data) throws IOException, XDocReportException {

		try {
			// 1) Load Docx file by filling Velocity template engine and cache
			// it to the registry
			String cheminabsoluprojet=new File(".").getAbsolutePath();
		
			InputStream in = new FileInputStream(cheminabsoluprojet.substring(0,cheminabsoluprojet.length()-1)
					+ "src\\main\\resources\\template\\"
					+ nametemplate
					+ ".docx");

			IXDocReport report = XDocReportRegistry.getRegistry().loadReport(
					in, TemplateEngineKind.Velocity);
			IContext context;
			// 2) Create fields metadata to manage lazy loop (#forech velocity)
			// for table row.
			// 1) Create FieldsMetadata by setting Velocity as template engine
			FieldsMetadata fieldsMetadata = report.createFieldsMetadata();
			// 2) Load fields metadata from Java Class
			context = report.createContext();
			Iterator iter = data.entrySet().iterator();
			while (iter.hasNext()) {
				Map.Entry ent = (Map.Entry) iter.next();

				String key = (String) ent.getKey();

				Object val = ent.getValue();
			
				if(val instanceof List)
				fieldsMetadata.load((String) key, ((List) val).get(0).getClass(),true);
				else if(val instanceof IImageProvider){
					
				fieldsMetadata.addFieldAsImage((String) key);
				report.setFieldsMetadata(fieldsMetadata);
				}
				else
				fieldsMetadata.load((String) key, val.getClass());

				

				context.put((String) key, val);
			}

			// 4) Generate report by merging Java model with the Docx
			OutputStream out = new FileOutputStream(new File(
					"src/main/resources/files/" + nameoutput + ".docx"));
			report.process(context, out);
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} catch (XDocReportException e) {
			e.printStackTrace();
			return false;
		}
		// catch (ClassNotFoundException e) {
		//
		// e.printStackTrace();
		// }

	}
}
